﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace Directory.Web
{
	public partial class Admin_Item : System.Web.UI.Page
	{
		protected string recommandKey = "isrecommand";
		protected string itemIdkey = "itemId";
		private string categoryIdKey = "categoryId";
		private string logoPathKey = "LogoPath";
		protected string logoBasePath = ConfigurationManager.AppSettings["LogoBasePath"].Replace("~/", "/");
		protected string rawLogoPath = "/default.gif";
		protected string returnPathKey = "from";
		protected string reffUrl = "ItemView.aspx";

		protected void Page_Load(object sender, EventArgs e)
		{

			this.RegularExpressionValidator1.ErrorMessage = Resources.Resource.NANMSG;
			this.btn_Delete.Attributes.Add("onclick", "return(window.confirm('确认删除该条目吗？'))");
			string action;
			action = Request.QueryString["action"];
			if (string.IsNullOrEmpty(action))
			{
				throw new ArgumentException("query parameter:action is need.");
			}
			try
			{
				reffUrl = ViewState["reffUrl"].ToString();
			}
			catch
			{
				reffUrl = Request.QueryString["from"];
			}
			ViewState["reffUrl"] = reffUrl;
			if (!IsPostBack)
			{
				switch (action.Trim().ToLower())
				{
					case "modify":
						RendForModify();
						break;
					case "delete":
						TryDeleteItem();
						break;
					case "additem":
						RendForAdd();
						break;
					case "recommand":
						Recommand();
						break;
					case "batchdelete":
						BatchDeleteItem();
						break;
					case "batchchecked":
						BatchCheckedItem();
						break;
					case "batchadd":
						RendForBatchAdd();
						break;
					default:
						return;
				}
			}
		}

		private void RendForModify()
		{
			pnlBatchAdd.Visible = false;
			this.btn_Add.Enabled = false;
			this.btn_Add.Visible = false;

			int itemId = 0;
			if (!int.TryParse(Request.QueryString[itemIdkey], out itemId))
			{
				Response.Write("<script>window.alert('参数不正确。');location.href='" + reffUrl + "'</script>");
				Response.End();
			}
			Directory.Model.ItemInfo itemInfo = ItemDataProxy.GetItemInfo(itemId);
			if (itemInfo == null)
			{
				Response.Write("<script>window.alert('" + Resources.Resource.Item + "不存在。');location.href='" + reffUrl + "'</script>");
				Response.End();
			}
			tbTitle.Text = itemInfo.Title;
			tbkeyWords.Text = itemInfo.KeyWords;
			tbDescription.Text = itemInfo.Description;
			tbLinkUrl.Text = itemInfo.LinkUrl;
			tbTopState.Text = itemInfo.TopState.ToString();
			rawLogoPath = itemInfo.LogoPath;
			tbLogopath.Text = itemInfo.LogoPath;

			IList<Directory.Model.CategoryInfo> catList = new List<Directory.Model.CategoryInfo>();
			if (!RoleDataProxy.IsUserInRole(Page.User.Identity.Name, WebSettings.GetInstance().RootCategoryAdminRole) && itemInfo.CategoryId == WebSettings.GetInstance().RootCategoryId)
			{
				Directory.Model.CategoryInfo cat = CategoryDataProxy.GetCategory(WebSettings.GetInstance().RootCategoryId);
				catList.Add(cat);
				CascadingCategory.SelectedIndex = 1;
			}
			else
			{
				catList = CategoryDataProxy.GetRootCategoriesForUser(Page.User.Identity.Name);
				IList<Directory.Model.CategoryInfo> parentPath = CategoryDataProxy.GetRecursiveParentsOfCategory(itemInfo.CategoryId);
				string pathStr = null;
				foreach (Directory.Model.CategoryInfo cat in parentPath)
				{
					pathStr += cat.CategoryId.ToString() + ",";
				}
				if (pathStr != null)
				{
					CascadingCategory.SelectedIndexStr = pathStr.Remove(pathStr.Length - 1);
					CascadingCategory.AutoLoad = true;
				}
			}
			CascadingCategory.DataSource = catList;
			CascadingCategory.DataBind();

			btn_Add.Enabled = false;
			btn_Add.Visible = false;
			if (itemInfo.IsChecked)
			{
				btn_Check.Enabled = false;
				btn_Check.Visible = false;
			}
			else
			{
				btn_Save.Enabled = false;
				btn_Save.Visible = false;
			}
		}

		private void RendForAdd()
		{
			pnlBatchAdd.Visible = false;
			this.btn_Check.Enabled = false;
			this.btn_Check.Visible = false;
			this.btn_Save.Enabled = false;
			this.btn_Save.Visible = false;
			this.btn_Delete.Enabled = false;
			this.btn_Delete.Visible = false;

			int categoryId;
			if (int.TryParse(Request.QueryString[categoryIdKey], out categoryId))
			{
				CascadingCategory.DataSource = CategoryDataProxy.GetRootCategoriesForUser(Page.User.Identity.Name);
				IList<Directory.Model.CategoryInfo> parentPath = CategoryDataProxy.GetRecursiveParentsOfCategory(categoryId);
				string pathStr = null;
				foreach (Directory.Model.CategoryInfo cat in parentPath)
				{
					pathStr += cat.CategoryId.ToString() + ",";
				}
				if (pathStr != null)
				{
					CascadingCategory.SelectedIndexStr = pathStr.Remove(pathStr.Length - 1);
					CascadingCategory.AutoLoad = true;
				}
				CascadingCategory.DataBind();
			}
		}

		private void RendForBatchAdd()
		{
			this.pnlDetail.Visible = false;
			int categoryId;
			if (int.TryParse(Request.QueryString[categoryIdKey], out categoryId))
			{
				CascadingCategory_bat.DataSource = CategoryDataProxy.GetRootCategoriesForUser(Page.User.Identity.Name);
				IList<Directory.Model.CategoryInfo> parentPath = CategoryDataProxy.GetRecursiveParentsOfCategory(categoryId);
				string pathStr = null;
				foreach (Directory.Model.CategoryInfo cat in parentPath)
				{
					pathStr += cat.CategoryId.ToString() + ",";
				}
				if (pathStr != null)
				{
					CascadingCategory_bat.SelectedIndexStr = pathStr.Remove(pathStr.Length - 1);
					CascadingCategory_bat.AutoLoad = true;
				}
				CascadingCategory_bat.DataBind();
			}
		}

		private void TryDeleteItem()
		{
			int itemId = 0;
			if (!int.TryParse(Request.QueryString[itemIdkey], out itemId))
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('query parameter:" + itemIdkey + " is need.');parent.ResetPage();</script>");
			}
			try
			{
				ItemDataProxy.DeleteItem(itemId);
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('删除成功。');parent.RefreshPage();</script>");
			}
			catch
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('删除失败：服务器错误。');parent.ResetPage();</script>");
			}
		}

		private void BatchDeleteItem()
		{
			string idList = null;
			try
			{
				idList = Request.QueryString[itemIdkey];
				string[] itemIdList = idList.Split(new char[] { ',' });
				string falseIdList = null;
				foreach (string idStr in itemIdList)
				{
					int Id;
					if (int.TryParse(idStr, out Id))
					{
						try
						{
							ItemDataProxy.DeleteItem(Id);
						}
						catch
						{
							falseIdList += Id.ToString() + ",";
						}
					}
				}
				if (falseIdList != null)
				{
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('以下条目删除失败：" + falseIdList.Remove(falseIdList.Length - 1) + "。');parent.RefreshPage();</script>");
				}
				else
				{
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('删除成功。');parent.RefreshPage();</script>");
				}
			}
			catch
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('query parameter:" + itemIdkey + " is need.');parent.ResetPage();</script>");
			}
		}

		private void BatchCheckedItem()
		{
			string idList = null;
			try
			{
				idList = Request.QueryString[itemIdkey];
				string[] itemIdList = idList.Split(new char[] { ',' });
				string falseIdList = null;
				foreach (string idStr in itemIdList)
				{
					int Id;
					if (int.TryParse(idStr, out Id))
					{
						try
						{
							ItemDataProxy.UpdateCheckState(Id, true);
						}
						catch
						{
							falseIdList += Id.ToString() + ",";
						}
					}
				}
				if (falseIdList != null)
				{
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('以下条目操作失败：" + falseIdList.Remove(falseIdList.Length - 1) + "。');parent.RefreshPage();</script>");
				}
				else
				{
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('操作成功。');parent.RefreshPage();</script>");
				}
			}
			catch
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('query parameter:" + itemIdkey + " is need.');parent.ResetPage();</script>");
			}
		}

		private void Recommand()
		{
			int itemId = 0;
			if (!int.TryParse(Request.QueryString[itemIdkey], out itemId))
			{
				throw new ArgumentException("query parameter:" + itemIdkey + " is need.");
			}
			bool IsRecommand;
			if (!bool.TryParse(Request.QueryString[recommandKey], out IsRecommand))
			{
				throw new ArgumentException("query parameter:" + recommandKey + " is need.");
			}
			try
			{
				ItemDataProxy.UpdateRecommandState(itemId, !IsRecommand);
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('操作成功。');parent.RefreshPage();</script>");
			}
			catch
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('操作失败：服务器错误。');parent.ResetPage();</script>");
			}
		}

		// 添加条目
		protected void btn_Add_Click(object sender, EventArgs e)
		{
			string logoPath = tbLogopath.Text; //Server.HtmlDecode(Request.Form[logoPathKey]);

			Directory.Model.ItemInfo.ErrorCode ErrorCode;
			int topState;
			if (!int.TryParse(tbTopState.Text, out topState))
			{
				topState = 0;
			}
			try
			{
				ItemDataProxy.CreateItem(CascadingCategory.SelectedId, tbTitle.Text, tbkeyWords.Text, tbDescription.Text, tbLinkUrl.Text, logoPath,
					Page.User.Identity.Name, Page.User.Identity.Name, int.Parse(tbTopState.Text), false, true, out ErrorCode);
			}
			catch (Exception ex)
			{
				ltMsg.Text = "服务器错误：" + ex.Message;
				return;
			}

			switch (ErrorCode)
			{
				case Directory.Model.ItemInfo.ErrorCode.Success:
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>window.alert('添加成功。');location.href='" + reffUrl + "'</script>");
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidTitle:
					ltMsg.Text = "添加失败：标题无效（不能为空）。";
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidCategory:
					ltMsg.Text = "添加失败：目录无效。";
					break;
				default:
					ltMsg.Text = "添加失败：未知错误 。";
					break;
			}
		}
		// 保存条目
		protected void btn_Save_Click(object sender, EventArgs e)
		{
			int itemId = 0;
			if (!int.TryParse(Request.QueryString[itemIdkey], out itemId))
			{
				throw new ArgumentException("query parameter:" + itemIdkey + " is need.");
			}
			Directory.Model.ItemInfo itemInfo = ItemDataProxy.GetItemInfo(itemId);
			itemInfo.Title = tbTitle.Text.Trim();
			itemInfo.KeyWords = tbkeyWords.Text.Trim();
			itemInfo.Description = tbDescription.Text.Trim();
			itemInfo.LinkUrl = tbLinkUrl.Text.Trim();
			int topstate;
			int.TryParse(tbTopState.Text, out topstate);
			itemInfo.TopState = topstate;

			itemInfo.LogoPath = tbLogopath.Text; //Server.UrlDecode(Request.Form[logoPathKey]);
			itemInfo.CategoryId = CascadingCategory.SelectedId;

			Directory.Model.ItemInfo.ErrorCode status;
			try
			{
				ItemDataProxy.UpdateItemInfo(itemInfo, out status);
			}
			catch (Exception ex)
			{
				ltMsg.Text = "服务器错误：" + ex.Message;
				return;
			}
			switch (status)
			{
				case Directory.Model.ItemInfo.ErrorCode.Success:
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>window.alert('保存成功。');location.href='" + reffUrl + "'</script>");
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidTitle:
					ltMsg.Text = "保存失败：标题无效（不能为空）。";
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidCategory:
					ltMsg.Text = "保存失败：目录无效。";
					break;
				default:
					ltMsg.Text = "保存失败：未知错误 。";
					break;
			}
		}
		// 通过审核
		protected void btn_Check_Click(object sender, EventArgs e)
		{
			int itemId = 0;
			if (!int.TryParse(Request.QueryString[itemIdkey], out itemId))
			{
				throw new ArgumentException("query parameter:" + itemIdkey + " is need.");
			}
			Directory.Model.ItemInfo itemInfo = ItemDataProxy.GetItemInfo(itemId);
			itemInfo.Title = tbTitle.Text.Trim();
			itemInfo.KeyWords = tbkeyWords.Text.Trim();
			itemInfo.Description = tbDescription.Text.Trim();
			itemInfo.LinkUrl = tbLinkUrl.Text.Trim();
			int topstate;
			int.TryParse(tbTopState.Text, out topstate);
			itemInfo.TopState = topstate;

			itemInfo.LogoPath = tbLogopath.Text; //Server.HtmlDecode(Request.Form[logoPathKey]);
			itemInfo.CategoryId = CascadingCategory.SelectedId;

			Directory.Model.ItemInfo.ErrorCode status;
			try
			{
				ItemDataProxy.UpdateItemInfo(itemInfo, out status);
				ItemDataProxy.UpdateCheckState(itemInfo.ItemId, true);	// 通过审核
			}
			catch (Exception ex)
			{
				ltMsg.Text = "服务器错误：" + ex.Message;
				return;
			}
			switch (status)
			{
				case Directory.Model.ItemInfo.ErrorCode.Success:
					ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>window.alert('保存并审核成功。');location.href='" + reffUrl + "'</script>");
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidTitle:
					ltMsg.Text = "保存失败：标题无效（不能为空）。";
					break;
				case Directory.Model.ItemInfo.ErrorCode.InvalidCategory:
					ltMsg.Text = "保存失败：目录无效。";
					break;
				default:
					ltMsg.Text = "操作失败：未知错误 。";
					break;
			}
		}
		// 删除条目
		protected void btn_Delete_Click(object sender, EventArgs e)
		{
			int itemId = 0;
			if (!int.TryParse(Request.QueryString[itemIdkey], out itemId))
			{
				throw new ArgumentException("query parameter:" + itemIdkey + " is need.");
			}
			try
			{
				ItemDataProxy.DeleteItem(itemId);
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>window.alert('删除成功。');location.href='" + reffUrl + "'</script>");
			}
			catch
			{
				ltMsg.Text = "删除失败：服务器错误。";
			}
		}
		// 批量添加条目
		protected void btnBatchAdd_Click(object sender, EventArgs e)
		{
			try
			{
				int categoryId;
				categoryId = CascadingCategory_bat.SelectedId;
				string title_bat = tbTitleBat.Text;
				string linkurl_bat = tbLinkUrlBat.Text;
				string[] title = title_bat.Split(new char[] { '\n' });
				string[] linkurl = linkurl_bat.Split(new char[] { '\n' });
				int count = title.Length < linkurl.Length ? title.Length : linkurl.Length;
				Directory.Model.ItemInfo.ErrorCode errorCode;
				for (int i = 0; i < count; i++)
				{
					if (string.IsNullOrEmpty(title[i]))
					{
						return;
					}
					ItemDataProxy.CreateItem(categoryId, title[i], string.Empty, string.Empty, linkurl[i], string.Empty, Page.User.Identity.Name, Page.User.Identity.Name, 0, false, true, out errorCode);
				}
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('添加完成');location.href='" + reffUrl + "'</script>");
			}
			catch (Exception ex)
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('添加失败：" + ex.Message + "');location.href='" + reffUrl + "'</script>");
			}
		}
	}
}